<?php
# FUNCTIONS_COMMON.PHP
# Common functions
# Included in every pages

if (!defined('INDEX')) exit;

///////////////////////////////////////////////////////////////////////////
// DISPLAY NUMBER
///////////////////////////////////////////////////////////////////////////
function number($number)
{
	return ($number)?number_format($number):0;
}

///////////////////////////////////////////////////////////////////////////
// REPLACE PRIVILEGE
// Action: 1=view,2=add,3=edit,4=delete,5=publish
///////////////////////////////////////////////////////////////////////////
function replace_privilege($string)
{
	$string = str_replace ('1','view',$string);
	$string = str_replace ('2','add',$string);
	$string = str_replace ('3','edit',$string);
	$string = str_replace ('4','delete',$string);
	$string = str_replace ('5','publish',$string);
	return $string;
}


///////////////////////////////////////////////////////////////////////////
// SHOW ICONS
///////////////////////////////////////////////////////////////////////////
function file_show_icon($file_name)
{
	if ( is_dir($file_name) )
		return '<img src="images/icon_file/icon_folder.png"  />';
	if($file_name)
	{
		$extension = strtolower(substr($file_name,-3));
		switch ($extension)
		{
			default:
				$icon = 'file';
			break;
			
			case "gif":
			case "jpg":
			case "bmp":
			case "png":
				$icon = 'jpg';
			break;
			
			case "mp3":
			case "wma":
			case "wmv":
			case "avi":
				$icon = 'mp3';
			break;
			
			case "rar":
			case "zip":
				$icon = 'zip';
			break;
			
			case "doc":
			case "rtf":
				$icon = 'doc';
			break;
			
			case "xls":
				$icon = 'xls';
			break;
			
			case "exe":
				$icon = 'exe';
			break;
			
			case "swf":
				$icon = 'swf';
			break;
			
			case "pdf":
				$icon = 'pdf';
			break;
			
			case "ppt":
				$icon = 'ppt';
			break;
			
			case "txt":
				$icon = 'txt';
			break;
			
		}
		$result = '<img src="images/icon_file/icon_'.$icon.'.gif"  />';
	}
	return $result;
}


///////////////////////////////////////////////////////////////////////////
// CUT STRING
///////////////////////////////////////////////////////////////////////////
function cut_string($string,$char)
{
	if(strlen($string) > $char)
	{
		for($x=$char;$x>$char-15;$x--)
		{
			if($string[$x]==" ") break;
		} 
		return substr($string,0,$x).'...';
	}
	else return $string;
}

///////////////////////////////////////////////////////////////////////////
// SHOW DATE 
///////////////////////////////////////////////////////////////////////////
function show_date($format,$time)
{
	global $cfg;
	if($time && $format) $result = gmdate($format, $time + (3600 * $cfg["default_timezone"]));
	else $result = '...';
	
	return $result;
}

function gmt($time){return $time-date('Z',$time);}
function gmt_diff($lt, $ut){return ($lt-$ut) / 3600;}
function mysql_date($timestamp){return date("Y-m-d", $timestamp);}
function mysql_datetime($timestamp){return date("Y-m-d H:i:s", $timestamp);}
function timestamp($mysql_datetime){return ($mysql_datetime>0)?strtotime($mysql_datetime):0;}
function convertDateTimeFormat($value){ //'dd-mm-yyyy' -> 'yyyy-mm-dd'
    list ($dd,$mm, $yyyy) = explode("-", $value);
    return "$yyyy-$mm-$dd";
}

///////////////////////////////////////////////////////////////////////////
// REPLACE SPECIAL CHARATERS IN STRING (USED TO INSERT,UPDATE DATA)
///////////////////////////////////////////////////////////////////////////
function data($string)
{
	$string = trim($string);
	//$string = str_replace ('\"','&quot;',$string);
	//$string = str_replace ("\'","'",$string);
	//$string = str_replace ('&','&amp;',$string);
	$string = str_replace ('"',"'",$string);
	//$string = str_replace ('<','&lt;',$string);
	//$string = str_replace ('>','&gt;',$string);
	//$string = stripslashes ($string);
	return $string;
}

function post_login($string)
{
	$variable = trim($_POST[$string]);
	$variable = str_replace ('"','&quot;',$variable);
	$variable = mysql_real_escape_string($variable);
	return $variable;
}

function post($string)
{
	return data($_POST[$string]);
}

function get($string)
{
	return data($_GET[$string]);
}

function replace_filename($string)
{
	$string = trim($string);
	$string = str_replace ('"','',$string);
	$string = str_replace ("'",'',$string);
	$string = str_replace (' ','',$string);
	$string = stripslashes ($string);
	return $string;
}

///////////////////////////////////////////////////////////////////////////
// GET CORRECT FORMAT OF URL (E.G RETURN TO 'HTTP://...')
///////////////////////////////////////////////////////////////////////////
function get_www($string)
{
	if($string)
	{
		if($string == "http://") return false;
		else
		{
			if(eregi("http://",$string)) return $string;
			else return "http://".$string;
		}
	}
	else return false;
}

///////////////////////////////////////////////////////////////////////////
// CHECK REQUIRED FIELD IN POST METHOD
///////////////////////////////////////////////////////////////////////////
function check_post($value)
{
	if($value)
	{
		$check_post = true;
		$value_array = explode(",",$value);
		foreach ($value_array as $value_id => $value_data)
		{
			if(!$_POST[$value_data]) 
			{
				$check_post = false;
				break;
			}
		}
	}
	return $check_post;
}

///////////////////////////////////////////////////////////////////////////
// CHECK VALID SESSION
///////////////////////////////////////////////////////////////////////////
function check_session_id()
{
	global $cfg;
	if(@$_POST["session_id"] && @$_POST["session_id"] == session_id())
		return true;
	else 
	{
		echo message("Session error! Please refresh this page and try again.",'error');
		return false;
	}
}

///////////////////////////////////////////////////////////////////////////
// CHECK VALID SESSION
///////////////////////////////////////////////////////////////////////////
function check_login_code($code)
{
	global $cfg;
	if(@$_POST["admin_login_code"] && @$_POST["admin_login_code"] == $_SESSION['admin_login_code'])
		return true;
	else 
	{
		echo message("Incorrect security code! Please try again.",'error');
		return false;
	}
}


///////////////////////////////////////////////////////////////////////////
// VALIDATE USING JAVASCRIPT
///////////////////////////////////////////////////////////////////////////
function js_validate($string,$form)
{
	global $lang;
	$result = '
		<script language="javascript">
		function validate_'.$form.'(){
	';
	$element_array = explode(",",str_replace(" ","",trim($string)));
	foreach ($element_array as $element)
	{
		$item = $form.'.'.$element;
		$result .= '
			if ('.$item.'.value == "")
			{	alert("'.$lang["js_required_info"].'");
				'.$item.'.focus();
				return false;}';
	}
	$result .= '
		else return true;
		}
		</script>';
	return $result;
}

///////////////////////////////////////////////////////////////////////////
// SHOW PAGE NUMBER
///////////////////////////////////////////////////////////////////////////
function show_pages($num_rows,$rows_per_page,$page)
{
	global $pg,$lang;
	if($num_rows && $rows_per_page && $page)
	{
		//$query = @mysql_query($sql);
		//$num_rows = @mysql_num_rows($query);
		$num_pages = @ceil($num_rows/$rows_per_page);
		$result = "";
		if ($num_pages >1)
		{
			$start_page = $_GET['pg'] - 5;
			$end_page = $_GET['pg'] + 5;
			$result .= '<table border="0" align="center" cellpadding="1" cellspacing="0"><tr>';
			if ($_GET["pg"] > 1) 
				$result .= '<td align=center width=20><input type="button" value=" &laquo; " style="font-size:10px;font-weight:bold;padding:0px" class="button" onClick="window.location=\''.$page.'&pg='.($_GET["pg"]-1).'\'" title="'.$lang["previous_page"].'"></td>';
			for ($x=(($start_page<1)?1:$start_page);$x<=(($end_page>$num_pages)?$num_pages:$end_page);$x++)
			{
				if ($_GET["pg"] == $x) $result .= '<td align=center width=20><u>'.$x.'</u></td>';
				else $result .= '<td align=center width=20><a href="'.$page.'&pg='.$x.'" title="Trang '.$x.'"><b>'.$x.'</b></a></td>';
			}
			if ($_GET["pg"] < $num_pages) 
			$result .= '<td align=center width=20><input type="button" value=" &raquo; " style="font-size:10px;font-weight:bold;padding:0px" class="button" onClick="window.location=\''.$page.'&pg='.($_GET["pg"]+1).'\'" title="'.$lang["previous_page"].'"></td>';
			$result .= '</tr><tr><td colspan=10 align=center><font class=info>Trang '.$_GET['pg'].' của '.$num_pages.' trang</font></td>';
			$result .= '</tr></table>';
			return $result;
		}
	}
	else return false;
}
///////////////////////////////////////////////////////////////////////////
// SHOW PAGE NUMBER
///////////////////////////////////////////////////////////////////////////
function show_pages_select($sql,$rows_per_page,$page)
{
	global $lang;
	if($sql && $rows_per_page && $page)
	{
		$query = @mysql_query($sql);
		$num_rows = @mysql_num_rows($query);
		$num_pages = @ceil($num_rows/$rows_per_page);
		$result = "";
		if ($num_pages >=1)
		{
			if ($_GET["pg"] > 1) 
			$result .=  '<input type="button" value="&lt;" style="font-size:10px;font-weight:bold;padding:0px" class="button" onClick="window.location=\''.$page.'&pg='.($_GET["pg"]-1).'\'" title="'.$lang["previous_page"].'">&nbsp;&nbsp;';
			$result .=  $lang["page"].' <select onChange="menu_jump(this.options[this.selectedIndex].value);" style="font-size:11px">';
			for ($x=1;$x<=$num_pages;$x++)
				$result .=  '<option value="'.$page.'&pg='.$x.'" '.(($_GET["pg"] == $x)?'style="color:red" selected':'').'>'.$x.'</option>';
			$result .=  '</select>';
			if ($_GET["pg"] < $num_pages) 
			$result .=  '&nbsp;&nbsp;<input type="button" style="font-size:10px;font-weight:bold;padding:0px" value="&gt;" class="button" onClick="window.location=\''.$page.'&pg='.($_GET["pg"]+1).'\'" title="'.$lang["next_page"].'">';
			//echo '<br /><font class="grey10">'.sprintf($lang["total_page"],$num_pages).'</font>';
		}
		return $result;
	}
	else return false;
}
///////////////////////////////////////////////////////////////////////////
// REDIRECT BROWSER
///////////////////////////////////////////////////////////////////////////
function redirect($url,$second)
{
	if ($url)
		echo '<meta http-equiv="REFRESH" content="'.$second.';url='.$url.'" />';
}

///////////////////////////////////////////////////////////////////////////
// SHOW MESSAGE
///////////////////////////////////////////////////////////////////////////
function message($msg,$type,$alert=0)
{
	global $lang;
	
	$color = array('error'=>'red','info'=>'blue');
	
	$message = '<font color='.$color[$type].'>'.str_replace('"','&quot;',$msg).'</font>';
	
	if($alert):
		$msg_tpl = '<script language="javascript">var message = "%s";</script>';
		$message = strip_tags($message);
	else:
		$msg_tpl = '<div style="padding:5px">
					<table width="500" cellpadding="5" cellspacing="1" border="0" align="center" style="border: 1px solid #C1CEDD">
					<tr>
					<td align="center" bgcolor="#E0E7ED" ><b>%s</b></td>
					</tr></table>
					</div>';
	
	endif;
	
	return sprintf($msg_tpl, $message);
	
}

///////////////////////////////////////////////////////////////////////////
// SHOW MESSAGE AND REDIRECT
///////////////////////////////////////////////////////////////////////////
function message_redirect($msg,$url)
{
	global $lang,$cfg;
	
	return '<meta http-equiv="REFRESH" content="'.$cfg["time_redirect"].';url='.$url.'" />
		<br /><br /><br />
		<table width="50%"  border="0" cellspacing="0" cellpadding="10" align="center">
  		<tr>
    	<td class="row1td" align="center" style="padding:10px">&nbsp;
				 <font color="blue"><b>'.$msg.'</b></font><br /><br />
				 <a href="'.$url.'">'.$lang["click_here"].'</a>
		</td>
  		</tr>
		</table>
		<br /><br /><br />';
	exit;
}

///////////////////////////////////////////////////////////////////////////
// RESIZE IMAGE (WITHOUT GD)
///////////////////////////////////////////////////////////////////////////
function show_thumb($image,$thumb_standard,$suffix=0)
{
	if ($image && $thumb_standard)
	{
		$dim = @getimagesize($image);
		if ($dim[0] > $thumb_standard && $dim[1] > $thumb_standard) 
			$percent = $dim[0]/$thumb_standard;
		else
		{
			if ($dim[0] > $thumb_standard) $percent = $dim[0]/$thumb_standard;
			elseif ($dim[1] > $thumb_standard) $percent = $dim[1]/$thumb_standard;
			else $percent = 1;
		}
		$sw = round($dim[0]/$percent);
		$sh = round($dim[1]/$percent);
		return '<img src="'.$image.'" width="'.$sw.'" height="'.$sh.'" '.$suffix.'>';
	}
}

///////////////////////////////////////////////////////////////////////////
// RESIZE IMAGE (USING GD)
///////////////////////////////////////////////////////////////////////////
function resize_jpg( $image_file_path, $new_image_file_path,$max_width=800, $max_height=800  )
{
//$resize_worked = resize_jpg("../pix/".$image_name, "../pix/"."thumb_".$image_name,88,88);
$return_val = 1;
$imagesize = getimagesize($image_file_path);
        switch ( $imagesize[2] ) {
            case 1:
              copy ( $image_file_path, $new_image_file_path );
                break;

           case 2:

    $return_val = ( ($img = ImageCreateFromJPEG ( $image_file_path )) && $return_val == 1 ) ? "1" : "0";


    $FullImage_width = imagesx ($img);
    $FullImage_height = imagesy ($img);

    $ratio =  ( $FullImage_width > $max_width ) ? (real)($max_width / $FullImage_width) : 1 ;
    $new_width = ((int)($FullImage_width * $ratio));
    $new_height = ((int)($FullImage_height * $ratio));

    $ratio =  ( $new_height > $max_height ) ? (real)($max_height / $new_height) : 1 ;
    $new_width = ((int)($new_width * $ratio));
    $new_height = ((int)($new_height * $ratio));


    if ( $new_width == $FullImage_width && $new_height == $FullImage_height )
        copy ( $image_file_path, $new_image_file_path );

    $full_id = ImageCreate( $new_width , $new_height );
    ImageCopyResized( $full_id, $img,
                    0,0,  0,0, //starting points
                    $new_width, $new_height,
                    $FullImage_width, $FullImage_height );



    copy ( $image_file_path, $new_image_file_path );
    $full_id =  imagecreatetruecolor ( $new_width , $new_height );
    imagecopyresampled( $full_id, $img,0,0,  0,0, //starting points
                    $new_width, $new_height,
                    $FullImage_width, $FullImage_height );


    $return_val = ( $full = ImageJPEG( $full_id, $new_image_file_path, 80 ) && $return_val == 1 ) ? "1" : "0";


    ImageDestroy( $full_id );
    break;
	        }
  return $return_val;
}

///////////////////////////////////////////////////////////////////////////
// SHOW LIST MENU
///////////////////////////////////////////////////////////////////////////
function show_select($default_value,$from,$to,$field)
{
	global $content;
	$result = "";
	$result .= '<select name="'.$field.'">';
	$result .= '<option value="">'.$default_value.'</option>';
	for($x=$from;$x<=$to;$x++)
	{
		$x = (($x<10)?'0'.$x:$x);
		$result .= '<option value="'.$x.'" '.((@$_POST[$field]==$x || @$content[$field]==$x)?'selected=true':'').'>'.$x.'</option>';
	}
	$result .= '</select>';
	return $result;
}

################################################################
# HÀM CONVERT STRING SANG CODE
# Chuyển chuỗi unicode thành code để hiển thị trên URL
# VD: Convert "Việt Nam đứng đầu thế giới về gạo?" => "viet-nam-dung-dau-the-gioi-ve-gao"
################################################################
function convert_string2code($string)
{
      if($string)
      {
            // Liệt kê ký tự Unicode
            $string_unicode =       'é,è,ẻ,ẽ,ẹ,ê,ế,ề,ể,ễ,ệ,ý,ỳ,ỷ,ỹ,ỵ,ú,ù,ủ,ũ,ụ,ư,ứ,ừ,ử,ữ,ự,í,ì,ỉ,ĩ,ị,ó,ò,ỏ,õ,ọ,ô,ố,ồ,ổ,ỗ,ộ,ơ,ớ,ờ,ở,ỡ,ợ,á,à,ả,ã,ạ,â,ấ,ầ,ẩ,ẫ,ậ,ă,ắ,ằ,ẳ,ẵ,ặ,đ,É,È,Ẻ,Ẽ,Ẹ,Ê,Ế,Ề,Ể,Ễ,Ệ,Ý,Ỳ,Ỷ,Ỹ,Ỵ,Ú,Ù,Ủ,Ũ,Ụ,Ư,Ứ,Ừ,Ử,Ữ,Ự,Í,Ì,Ỉ,Ĩ,Ị,Ó,Ò,Ỏ,Õ,Ọ,Ô,Ố,Ồ,Ổ,Ỗ,Ộ,Ơ,Ớ,Ờ,Ở,Ỡ,Ợ,Á,À,Ả,Ã,Ạ,Â,Ấ,Ầ,Ẩ,Ẫ,Ậ,Ă,Ắ,Ằ,Ẳ,Ẵ,Ặ,Đ';
			// Liệt kê ký tự không dấu (cùng array key với ký tự Unicode)
            $string_abc =           'e,e,e,e,e,e,e,e,e,e,e,y,y,y,y,y,u,u,u,u,u,u,u,u,u,u,u,i,i,i,i,i,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,o,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,d,E,E,E,E,E,E,E,E,E,E,E,Y,Y,Y,Y,Y,U,U,U,U,U,U,U,U,U,U,U,I,I,I,I,I,O,O,O,O,O,O,O,O,O,O,O,O,O,O,O,O,O,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,D';
			// Ký tự đặc biệt (google không hiểu những ký tự này)
            $string_special =       "` ! @ # $ % ^ * \ / ; ' ( ) - = { } [ ] | : , . ? / < >";
			// Ký tự kết nối từ (sẽ được thay bằng -)
            $string_connector = "&,+,_, ";
            
            // Tạo mảng
            $string_unicode_array = explode(",",$string_unicode);
            $string_abc_array = explode(",",$string_abc);
            $string_special_array = explode(" ",$string_special);
            $string_connector_array = explode(",",$string_connector);
            
			// Bỏ khỏang trắng hai đầu
            $string = trim($string);
            // Convert unicode->abc
            $string = str_replace($string_unicode_array, $string_abc_array, $string);
            // Bỏ ký tự đặc biệt
            $string = str_replace($string_special_array, '', $string);
            // Tạo kết nối giữa các từ bằng -
            $string = str_replace($string_connector_array, '-', $string);
            // Chuyển thành chữ thường
            $string = strtolower($string);
            
            return $string;
      }
}


################################################################
# CONVERT CHUỖI THÀNH SỐ
# VD: "1,550,000 VND => "1550000"
################################################################
function convert2number($number)
{
	$number = ereg_replace("([A-Za-z_]+)","",$number);
	$number = str_replace(",","",$number);
	$number = str_replace(".","",$number);
	return $number;
}
?>
